package org.dromara.pay.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.business.service.UserService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.pay.constant.TopUpConstant;
import org.dromara.pay.domain.ReportVo;
import org.dromara.pay.domain.TopUp;
import org.dromara.pay.service.TopUpService;
import org.dromara.system.domain.SysUser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 系统充值订单
 *
 * @author zlj
 * @date 2024-05-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/topUp")
public class TopUpController extends BaseController {

    private final TopUpService topUpService;

    /**
     * 根据订单id查询充值订单
     */
    @GetMapping("/getByOrderId")
    public R<TopUp> getByOrderId(Long orderId) {
        return R.ok(topUpService.getByOrderId(orderId));
    }

    /**
     * 查询系统充值订单列表
     */
    @SaCheckPermission("pay:topUp:list")
    @GetMapping("/list")
    public TableDataInfo<TopUp> list(TopUp bo, PageQuery pageQuery) {
        return topUpService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出系统充值订单列表
     */
    @SaCheckPermission("pay:topUp:export")
    @Log(title = "系统充值订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TopUp bo, HttpServletResponse response) {
        List<TopUp> list = topUpService.queryList(bo);
        ExcelUtil.exportExcel(list, "系统充值订单", TopUp.class, response);
    }

    /**
     * 获取系统充值订单详细信息
     *
     * @param topUpId 主键
     */
    @SaCheckPermission("pay:topUp:query")
    @GetMapping("/{topUpId}")
    public R<TopUp> getInfo(@NotNull(message = "主键不能为空")
                            @PathVariable Long topUpId) {
        return R.ok(topUpService.queryById(topUpId));
    }

    /**
     * 新增系统充值订单
     */
    @SaCheckPermission("pay:topUp:add")
    @Log(title = "系统充值订单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TopUp bo) {
        return toAjax(topUpService.insertByBo(bo));
    }

    /**
     * 修改系统充值订单
     */
    @SaCheckPermission("pay:topUp:edit")
    @Log(title = "系统充值订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TopUp bo) {
        return toAjax(topUpService.updateByBo(bo));
    }

    /**
     * 删除系统充值订单
     *
     * @param topUpIds 主键串
     */
    @SaCheckPermission("pay:topUp:remove")
    @Log(title = "系统充值订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{topUpIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] topUpIds) {
        return toAjax(topUpService.deleteWithValidByIds(List.of(topUpIds), true));
    }

    /**
     * 图标库位置: ruoyi-modules/ruoyi-pay/src/main/resources/icon.text
     */
    @GetMapping("/report")
    public R<List<ReportVo>> report() {
        List<TopUp> list = topUpService.lambdaQuery().eq(TopUp::getStatus, TopUpConstant.STATUS_FINISH).list();
        Date now = new Date();
        //今日收款
        BigDecimal today = list.stream().filter(t -> DateUtil.isSameDay(t.getSuccessTime(), now))
            .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        //昨日收款
        BigDecimal yesterday = list.stream().filter(t -> DateUtil.isSameDay(t.getSuccessTime(), DateUtil.offsetDay(now, -1)))
            .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        //本月收款
        BigDecimal month = list.stream().filter(t -> DateUtil.isSameMonth(t.getSuccessTime(), now))
            .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        //上月收款
        BigDecimal lastMonth = list.stream().filter(t -> DateUtil.isSameMonth(t.getSuccessTime(), DateUtil.lastMonth()))
            .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        //本年收款
        BigDecimal year = list.stream().filter(t -> DateUtil.isSameDay(DateUtil.beginOfYear(t.getSuccessTime()), DateUtil.beginOfYear(now)))
            .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        //总收款
        BigDecimal all = list.stream().map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);

        List<ReportVo> list1 = Arrays.asList(
            new ReportVo("今日收款(元)", today, "👀"),
            new ReportVo("昨日收款(元)", yesterday, "📥"),
            new ReportVo("本月收款(元)", month, "📢"),
            new ReportVo("上月收款(元)", lastMonth, "🌤️"),
            new ReportVo("本年收款(元)", year, "✍"),
            new ReportVo("总收款(元)", all, "🚀")
        );
        return R.ok(list1);
    }
    private final UserService userService;
    @GetMapping("/userReport")
    public R<List<ReportVo>> userReport() {
        List<SysUser> list = userService.lambdaQuery()
            .eq(SysUser::getStatus, "0").list();
        //系统用户数量
        long sysUserNum = list.stream().filter(t -> ObjectUtil.equal(t.getUserType(), UserType.SYS_USER.getUserType())).count();
        //客户数量
        long xcxUserNum = list.stream().filter(t -> ObjectUtil.equal(t.getUserType(), UserType.XCX_USER.getUserType())).count();
        //今日注册
        long dayUserNum = list.stream().filter(t -> DateUtil.isSameDay(t.getCreateTime(), new Date())).count();
        //本月注册
        long monthUserNum = list.stream().filter(t -> DateUtil.isSameMonth(t.getCreateTime(), new Date())).count();
        List<ReportVo> repost = Arrays.asList(
            new ReportVo("系统用户数量", new BigDecimal(sysUserNum), "☀"),
            new ReportVo("客户数量", new BigDecimal(xcxUserNum), "❤"),
            new ReportVo("今日注册", new BigDecimal(dayUserNum), "♔"),
            new ReportVo("本月注册", new BigDecimal(monthUserNum), "⏱")
        );
        return R.ok(repost);
    }

    @GetMapping("/echartsReport")
    public R<Map<String, List<Object>>> echartsReport() {
        Date now = new Date();
        List<TopUp> list = topUpService.lambdaQuery()
            .ge(TopUp::getSuccessTime, DateUtil.beginOfDay(DateUtil.offsetDay(now, -29)))
            .eq(TopUp::getStatus, TopUpConstant.STATUS_FINISH).list();

        //每日收款
        List<Object> dataList = new ArrayList<>(30);
        List<Object> dayList = new ArrayList<>(30);
        for (int i = 29; i >= 0; i--) {
            Date date = DateUtil.offsetDay(now, -i);
            BigDecimal today = list.stream().filter(t -> DateUtil.isSameDay(t.getSuccessTime(), date))
                .map(TopUp::getPayerTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
            dataList.add(today.stripTrailingZeros().toPlainString());
            dayList.add(DateUtil.format(date, "MM.d"));
        }

        return R.ok(Map.of(
            "data", dataList,
            "xAxis", dayList
        ));
    }
}
